//
//  WBEmoticonsBundle.swift
//  weibo
//
//  Created by  郭航 on 16/7/5.
//  Copyright © 2016年 郭航. All rights reserved.
//

import UIKit

/// 行
let EmoticonsMaxRow = 7
/// 列
let EmoticonsMaxCol = 3
/// 能显示的最多因素
private let EmoticonsMaxCount = EmoticonsMaxRow * EmoticonsMaxCol - 1

class WBEmoticonsBundle: NSObject {

    static let shareEmoticonsBundle: WBEmoticonsBundle = WBEmoticonsBundle()

    lazy var bundle: NSBundle = {
        let path = NSBundle.mainBundle().pathForResource("Emoticons", ofType: "bundle")!
        return NSBundle(path: path)!
    }()
    
    lazy var defaultEmoticons: [WBEmoticonModel] = {
        return self.getEmoticons("default")
    }()
    
    lazy var emojiEmoticons: [WBEmoticonModel] = {
        return self.getEmoticons("emoji")
    }()
    
    lazy var lxhEmoticons: [WBEmoticonModel] = {
        return self.getEmoticons("lxh")
    }()
    
    lazy var emoticons: [[[WBEmoticonModel]]] = {
        return [
            self.getEmoticonsGroup(self.defaultEmoticons),
            self.getEmoticonsGroup(self.emojiEmoticons),
            self.getEmoticonsGroup(self.lxhEmoticons),
                ]
    }()
    
    private func getEmoticons(fileName: String) -> [WBEmoticonModel] {
        let path = bundle.pathForResource("\(fileName)/info", ofType: ".plist")!
        let array = NSArray(contentsOfFile: path)!
        var arrayM = [WBEmoticonModel]()
        
        for dic in array {
            let model = WBEmoticonModel(dic: (dic as? [String : AnyObject])!)
            model.path = "\(fileName)/"
            arrayM.append(model)
        }
        
        return arrayM
    }
    
    private func getEmoticonsGroup(Emoticons: [WBEmoticonModel]) -> [[WBEmoticonModel]] {
        let pageNum = (Emoticons.count + EmoticonsMaxCount-1) / EmoticonsMaxCount
        
        var emoticonsGroup = [[WBEmoticonModel]]()
        for i in 0 ..< pageNum {
            let loc = i * EmoticonsMaxCount
            var count = EmoticonsMaxCount
            if (loc + count) > Emoticons.count {
                count = Emoticons.count - loc
            }
        
            emoticonsGroup.append((Emoticons as NSArray).subarrayWithRange(NSRange(location: loc, length: count)) as! [WBEmoticonModel])
        }
        
        return emoticonsGroup
    }
    
    func searchEmoticonsPngName(string: String) -> String? {
        for emoticon in defaultEmoticons {
            if string == emoticon.chs {
                return emoticon.pngName
            }
        }
        
        for emoticon in lxhEmoticons {
            if string == emoticon.chs {
                return emoticon.pngName
            }
        }
        
        return nil
    }
    
}
